package com.addressbook.fw;

import java.util.HashSet;
import java.util.List;
//import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.addressbook.tests.GroupObject;

public class GroupHelper extends HelperWithWebDriverBase {

	private Groups groupCache;
	public GroupHelper(ApplicationManager manager) {
		super(manager);
	}

	public void createGroup(GroupObject group) {
		manager.getNavigationHelper().openGroupPage();
		initGroupCreation();
		fillGroupForm(group);
		submitGroupCreation();
		manager.getNavigationHelper().openGroupPage();
		groupCache = null;
	}

	private void submitGroupCreation() {
		click(By.name("submit"));
	}

	private void fillGroupForm(GroupObject groupObject) {
		fillField("group_name", groupObject.name);
		fillField("group_header", groupObject.header);
		fillField("group_footer", groupObject.footer);
	}

	private void initGroupCreation() {
		click(By.name("new"));
	}

	public void deleteGroup(int i) {
		manager.getNavigationHelper().openGroupPage();
		checkGroup(i);
		click(By.name("delete"));
		manager.getNavigationHelper().openGroupPage();
		groupCache = null;
	}

	public void modifyGroup(int i, GroupObject group) {
		manager.getNavigationHelper().openGroupPage();
		initGroupModification(i);
		fillGroupForm(group);
		submitGroupModification(i);
		manager.getNavigationHelper().openGroupPage();
		groupCache = null;
	}

	private void submitGroupModification(int i) {
		click(By.name("update"));
	}

	private void initGroupModification(int i) {
		checkGroup(i);
		click(By.name("edit"));
	}

	private void checkGroup(int i) {
		click(By.name("selected[]"));
	}

	public Groups getGroups() {
		if (groupCache == null) {
			buildGroupCache();
		}
		return groupCache;		
	}
	
	private void buildGroupCache(){
		HashSet<GroupObject> set = new HashSet<GroupObject>();
		manager.getNavigationHelper().openGroupPage();
		List<WebElement> checkboxes = findElements(By.name("selected[]"));
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			Pattern p = Pattern.compile(".*\\((.*)\\)");
			Matcher m = p.matcher(title);
			if (m.matches()) {
				title = m.group(1);
			}
			GroupObject group = new GroupObject().setName(title).setId(checkbox.getAttribute("value"));
			set.add(group);
		}
		groupCache = new Groups(set);
	}
}
